 #include "flash.h"  
 #include <stdio.h>
 #define Path_page  (0x08000000 +0xE0000)

 #define CACHE_SIZE       (2048 /4)  
DoubleFlash cache[CACHE_SIZE]; 
 
uint16_t inited=0;  
 
static uint32_t readFlash32(uint32_t addr){
    return *((__IO uint32_t *)addr);
} 
static uint8_t readFlash8(uint32_t addr){
    return *((__IO uint8_t *)addr);
}
static uint16_t readFlash16(uint32_t addr){
    return *((__IO uint16_t *)addr);
} 
void Flash_init(void ){ 
    for(uint16_t i=0;i<CACHE_SIZE;i++){ 
        cache[i].w = readFlash32(  Path_page+i*4);  
    } 
    inited=1;
}
void setCacheDecimal(uint32_t addr,float d){ 
     if(addr>=cache[0].h[0]*2+1){
        printf("setCacheDecimal out length %d",addr);
        return ;
     }
     cache[addr].d = d;
}
    
float getCacheDecimal(uint32_t addr){
    if(addr>=cache[0].h[0]*2+1){
        printf("getCacheDecimal out length %d",addr);
        return 0;
     }	
    return cache[addr].d ;
}
void setCacheInt32(uint32_t addr,uint32_t w1){
    if(addr>=cache[0].h[0]*2+1){
        printf("setCacheInt32 out length %d",addr);
        return ;
    }	
    cache[addr].w =w1;
         
}
void setCacheInt16(uint32_t addr,uint8_t i, uint16_t  h){
    	
     cache[addr].h[i]=h ;
}
void setCacheInt8(uint32_t addr,uint8_t i, uint8_t  b){
    if(addr>=cache[0].h[0]*2+1){
        printf("setCacheInt8 out length %d",addr);
        return ;
    }	
    cache[addr].b[i] = b;

}
     
uint8_t getCacheInt8(uint32_t addr,uint8_t  index){ 
        if(addr>=cache[0].h[0]*2+1){
            printf("getCacheInt8 out length %d",addr);
            return 0;
         }	
    return cache[addr].b[index] ;
}
uint16_t getCacheInt16(uint32_t addr,uint8_t  index){ 
       
    return cache[addr].h[index] ;
}
uint32_t getCacheInt32(uint32_t addr ){
    if(addr>=cache[0].h[0]*2+1){
        printf("getCacheInt32 out length %d",addr);
        return 0;
     }	 
     return cache[addr].w ;
     
}
    
void saveCache(void){
    if(!inited){
        return;
    }
    printf("save flashing");
    FLASH_Unlock();
    FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | 
                      FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); 
    FLASH_Status s= FLASH_EraseSector(FLASH_Sector_11,VoltageRange_4); 
    for(uint16_t i=0;i<cache[0].h[0]*2+1;i++){ 
        FLASH_Status s=FLASH_ProgramWord(  Path_page+i*4, cache[i].w);  
        printf("%d",s);
      
    }
    FLASH_Lock(); 
}


void getUid(int8_t * dir){
        for(int8_t i=0;i<12;i++ ){
            dir[i]=readFlash8(0x1FFF7A10+i);
        } 
}
uint16_t getFiashSize(void ){ 
        return readFlash16(0x1FFF7A22);
}
